url = "/Users/liupeng/learn/python3.12/python_django/manage.py"


# 读取文件
def readFile():
    # read() - 读取所有
    with open(url, 'r') as file:
        content = file.read()
    print(content)

    # readline() - 按行读取，读取时候占用内存小，比较适合大文件
    with open(url, 'r') as file:
        line = file.readline()
        while line:
            print(line)
            line = file.readline()
    with open(url, 'r') as file:
        for line in file:
            print(line)

    # readlines() - 读取整个文件所有行，保存在一个列表（list）变量中，每次读取一行，但读取大文件会比较占内存
    with open(url, 'r') as file:
        lines = file.readlines()
    for line in lines:
        print(line)
    file.close()


# 写入文件
def writeFile():
    # 使用write()方法
    file = open(url, "w")
    file.write("测试一下子")
    file.close()

    # 使用withy语句
    with open(url, 'w') as file:
        file.write('哈哈')

    # 使用writeline()方法
    with open(url, 'w') as file:
        lines = ["11", "22"]
        file.writelines(lines)

    # 使用print()函数
    with open(url, 'w') as file:
        print('测试print函数', file=file)


def fileStrReplace():
    with open(url, 'r') as file:
        content = file.read()
    newContent = content.replace('print', 'haha')
    print(newContent)


if __name__ == '__main__':
    readFile()
